package com.shadt.cloud.dao.impl;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Repository;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shadt.cloud.dao.RecordDao;
import com.shadt.cloud.vo.RecordVo;
import com.shadt.core.dao.impl.BaseDaoImpl;

/**
 * 记录信息数据访问层实现类
 * 
 * @author SongR
 *
 */
@Repository
public class RecordDaoImpl extends BaseDaoImpl<RecordVo> implements RecordDao {
	@SuppressWarnings("rawtypes")
	public List getBySql(String sql) {
		return this.getJdbcTemplate().queryForList(sql);
	}

	Logger log = Logger.getLogger(this.getClass());

	/**
	 * 新增 redis <br>
	 * ------------------------------<br>
	 * 
	 * @return
	 */
	public boolean addList(final String key, final List<RecordVo> vos) {
		ZSetOperations<String, String> ops2 = redisTemplate.opsForZSet();
		for (RecordVo r : vos) {
			ops2.add(key, JSONObject.toJSONString(r),Integer.parseInt(r.getId()));
		}
//		Set<String> s =ops2.rangeByScore("test", 0.1, 0.3);
//		for (String ss : s) {
//			System.out.println(ss);
//		}
//		
//		BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(key);
//		for (RecordVo r : vos) {
//			ops.put(r.getId(), JSONObject.toJSONString(r));
//		}
//		ops.persist();//删除过期(如果有的话)的数据。
		// redisTemplate.delete("student");
		// REDISTEMPLATE.DELETE("STUDENT:1");
		// ops.put("cs01", "123");// 存入数据 ops.putAll(maps); 存入多条数据
		// String key1 = ops.getKey();// tableName的名字
		// System.out.println("key1:" + key1+key);
		// String key11 = ops.get("cs01");
		// System.out.println("key11:" + key11+key);// 获取key的值
		// ops.putIfAbsent("cs02", "456");
		// String key2 = ops.getKey();
		// System.out.println("ops.getKey()-key2:" + key2);
		// String key21 = ops.get("cs02");
		// System.out.println("ops.get(cs02)-key21:" + key21);
		//
		// 
		// System.out.println("ops.getExpire():" + ops.getExpire());// -1
		// System.out.println("ops.expireAt(new Date()):"
		// + ops.expireAt(new Date()));// true 设置生存过期时间
		// System.out.println("ops.getType():" + ops.getType());// Hash
		// System.out.println("ops.hasKey(cs01):" + ops.hasKey("cs01"));// true
		// System.out.println("ops.hasKey(cs02):" + ops.hasKey("cs02"));// true

		// Set<String> keys = ops.keys();// 获取所有的key
		// for (String string : keys) {
		// System.out.println("ops.keys():" + string);
		// }
		//
		// System.out.println("ops.values():" + ops.values());// 获取所有的value
		// System.out.println("ops.size():" + ops.size());// 2 获取数量
		//
		// ops.delete("cs01");// 删除key为cs01的数据

		// boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
		// public Boolean doInRedis(RedisConnection connection)
		// throws DataAccessException {
		// RedisSerializer<String> serializer = getRedisSerializer();
		// byte[] keys = serializer.serialize(key);
		// byte[] value = serializer.serialize(JSONObject.toJSONString(vos));
		// return connection.setNX(keys, value);
		// }
		// });
		// this.redisTemplate.expire(key,time,TimeUnit.MILLISECONDS);
		// log.info("成功保存栏目"+key+"到redis中"+vos.size()+"条记录");
		return true;
	}

	@Override
	public List<RecordVo> getList(final String key) {

		String s = redisTemplate.execute(new RedisCallback<String>() {
			public String doInRedis(RedisConnection connection) throws DataAccessException {
				RedisSerializer<String> serializer = getRedisSerializer();
				byte[] keys = serializer.serialize(key);
				byte[] value = connection.get(keys);
				if (value == null) {
					return null;
				}
				String t = "";
				try {
					t = new String(value, "utf-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				return t;
			}
		});
		List<RecordVo> vos = new ArrayList<RecordVo>();
		if (s != null && !s.equals("")) {
			JSONArray arr = JSONArray.parseArray(s);
			if (arr.size() > 0) {
				for (Object obj : arr) {
					JSONObject o = (JSONObject) obj;
					RecordVo vo = JSONObject.parseObject(o.toJSONString(), RecordVo.class);
					vos.add(vo);
				}
			}
		}
		log.info("成功从redis中获取栏目" + key + "，" + vos.size() + "条记录");
		return vos;
	}

	public List<RecordVo> getList(String key,  Long max,Integer start, Integer size) {
		List<RecordVo> array= new ArrayList<RecordVo>();
		ZSetOperations<String, String> ops2 = redisTemplate.opsForZSet();
		Set<String> s =ops2.rangeByScore(key, 0, max, start, size);
		for (String ss : s) {
			RecordVo vo = JSONObject.parseObject(ss,RecordVo.class);
			array.add(vo);
		}
		log.info("成功从redis中获取栏目" + key + "," + array.size() + "条记录");
		return array;
	}
}
